package com.smart.controller;

import java.util.Map;
import java.util.HashMap;
import java.io.IOException;
import javax.imageio.ImageIO;
import com.smart.util.Messages;
import javax.annotation.Resource;
import io.swagger.annotations.Api;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.codec.Base64;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import com.smart.service.CaptchaService;
import io.swagger.annotations.ApiOperation;
import javax.servlet.http.HttpServletResponse;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * @author lgb
 * @date 2020年6月8日 下午8:11:57
 * Copyright (C) 深圳工勘科技
 * @说明: 生成图片验证码
 **/
@RestController
@Api(tags = "Sys-captcha => 图形验证码")
public class CaptchaController {
	
	@Resource
    private CaptchaService captchaService;
	
	 /**
     * 生成验证码
	 * @throws IOException 
     */
    @ApiOperation("captchaImage => 生成验证码")
    @GetMapping("captchaImage")
    public Messages<Map<String, Object>> captcha(HttpServletResponse response) throws IOException{
        response.setHeader("Cache-Control", "no-store, no-cache");
        response.setContentType("image/jpeg");
        // 唯一标识
        String uuid = IdUtil.simpleUUID();
        //获取图片验证码
        BufferedImage image = captchaService.getCaptcha(uuid);
        Map<String, Object> map = new HashMap<>();
        ByteArrayOutputStream stream = new ByteArrayOutputStream();

        ImageIO.write(image, "jpg", stream);
        map.put("uuid", uuid);
        map.put("img", Base64.encode(stream.toByteArray()));
        return Messages.success(map);
    }
	
}